package org.veloxbot.api.internals.concurrent;

/**
 * @author Velox
 */
public abstract class LoopTask extends Task {

	/*
	 * What to do when the LoopTask is executed.
	 * 
	 * @return The amount of time to sleep for.
	 */
	public abstract int loop();

	private boolean stopped = false;

	private boolean paused = false;

	/**
	 * Stops the LoopTask.
	 */
	public void terminate() {
		stopped = true;
	}

	/**
	 * Gets whether the LoopTask is paused or not.
	 *
	 * @return Whether the LoopTask is paused or not.
	 */
	public boolean isPaused() {
		return paused;
	}

	/**
	 * Sets the script's pause variable corresponding to the given parameter.
	 *
	 * @param paused <t>true</t> to pause the LoopTask, otherwise resume the LoopTask.
	 */
	public void setPause(final boolean paused) {
		this.paused = paused;
	}

	/**
	 * Runs the LoopTask
	 */
	@Override
	public final void run() {
		if (stopped) {
			terminate();
		} else if (paused) {
			try {
				Thread.sleep(10);
			} catch (final InterruptedException ignored) {
			}
			run();
		} else {
			final int sleep = loop();
			if (sleep < 0) {
				terminate();
			} else {
				try {
					Thread.sleep(sleep);
				} catch (final InterruptedException ignored) {
				}
				run();
			}
		}
	}
}
